// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package config

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v3"
)

type MongoCfg struct {
	Url      string `yaml:"url"`
	DataBase string `yaml:"dataBase"`
}

type ExtensionServerCfg struct {
	RemoteAddr string `yaml:"remoteAddr"`
}

type RedisCfg struct {
	Addr     string `yaml:"addr"`
	PassWord string `yaml:"passWord"`
}

type DataBaseCfg struct {
	Mongo     MongoCfg           `yaml:"mongo"`
	FileStore ExtensionServerCfg `yaml:"fileStore"`
	Redis     RedisCfg           `yaml:"redis"`
}

type WxLoginCfg struct {
	AppId     string `yaml:"appId"`
	AppSecret string `yaml:"appSecret"`
}

type LoginCfg struct {
	Wx WxLoginCfg `yaml:"wx"`
}

type ServerConfig struct {
	ServPort    uint16      `yaml:"servPort"`
	TlsCertFile string      `yaml:"tlsCertFile"`
	TlsKeyFile  string      `yaml:"tlsKeyFile"`
	DataBase    DataBaseCfg `yaml:"dataBase"`
	Login       LoginCfg    `yaml:"login"`
}

func ReadConfig(fileName string) (*ServerConfig, error) {
	data, err := os.ReadFile(fileName)
	if err != nil {
		return nil, err
	}
	servCfg := &ServerConfig{}
	err = yaml.Unmarshal(data, servCfg)
	if err != nil {
		return nil, err
	}
	//check config
	if servCfg.TlsCertFile == "" && servCfg.TlsKeyFile != "" {
		return nil, fmt.Errorf("miss tlsCertFile config")
	}
	if servCfg.TlsCertFile != "" && servCfg.TlsKeyFile == "" {
		return nil, fmt.Errorf("miss tlsKeyFile config")
	}
	return servCfg, nil
}
